<?php
namespace Common\Model;

class AderModel extends UserModel {
    const TYPE = 2; //2表示广告主

    public function getById($id) {
        $expr = [            
            'type' => self::TYPE,
            'id'   => $id,
        ];

        $r = $this->where($expr)->find();

        return $r;
    }

    public function save2($d) {
        $id = empty($d['id']) ? 0 : (int)$d['id'];
        $d['type'] = self::TYPE;

        try {
            $r = parent::save2($d);

            if (empty($id)) {
                $id = $r;
            }

            cacheApi('ader', [
                'a'  => (empty($d['id']) ? 'add' : 'modify'),
                'id' => $id,
            ]);
        } catch(\Exception $e) {
            throw new \Exception($e->getMessage());
        }

        return true;
    }

    /**
     * del
     *
     * @param mixed $id
     * @return void
     */
    public function del($id) {
        $id   = (int)$id;
        $expr = [
            'type' => self::TYPE,
            'id'   => $id,
        ];

        if (!$record = $this->where($expr)->find()) {
            return true;
        }

        if ($record['money_1'] > 0) {
            throw new \Exception('此广告主还有余额，不能删除');
        }

        if (D('Plan')->where(['uid' => $id])->find()) {
            throw new \Exception('此广告主还有广告计划，不能删除');
        }

        try {
            cacheApi('ader', [
                'a'  => 'del',
                'id' => $id,
            ]);
        } catch(\Exception $e) {
            throw new \Exception($e->getMessage());
        }

        return $this->where($expr)->delete();
    }

    /**
     * getMoneyById
     * 返回广告主余额
     *
     * @param mixed $id
     * @return void
     */
    public function getMoneyById($id) {
        $id = (int)$id;

        if(empty($id)) {
            return false;
        }

        $expr = ['id' => $id];

        return $this->where($expr)->getField('money_1');
    }

    /**
     * changeStatus
     *
     * todo:如果是锁定广告主，那么其投放中的广告计划也应该被停止
     *
     * @param mixed $id
     * @param mixed $status
     * @return void
     */
    public function changeStatus($id, $status) {
        parent::changeStatus($id, $status);

        try {
            cacheApi('ader', [
                'a'  => 'modify',
                'id' => $id,
            ]);
			
        } catch(\Exception $e) {
            throw new \Exception($e->getMessage());
        }

        return true;
    }

}
